from flask import Flask, request, send_file, jsonify
import os
from f5tts_module import F5TTS

app = Flask(__name__)

UPLOAD_FOLDER = './uploads'
OUTPUT_FOLDER = './outputs'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER

for folder in [UPLOAD_FOLDER, OUTPUT_FOLDER]:
    if not os.path.exists(folder):
        os.makedirs(folder)

f5tts = F5TTS()

# API endpoint to accept ref_audio, ref_text, and gen_text
@app.route('/process', methods=['POST'])
def process_data():

    if 'ref_audio' not in request.files:
        return jsonify({"error": "No ref_audio part"}), 400

    ref_audio = request.files['ref_audio']

    if ref_audio:
        audio_path = os.path.join(app.config['UPLOAD_FOLDER'], ref_audio.filename)
        ref_audio.save(audio_path)
    else:
        return jsonify({"error": "Failed to upload the audio file"}), 400

    ref_text = request.form.get('ref_text')
    gen_text = request.form.get('gen_text')

    if not ref_text or not gen_text:
        return jsonify({"error": "Missing ref_text or gen_text"}), 400

    output_wave_path = os.path.join(app.config['OUTPUT_FOLDER'], 'out.wav')

    try:
        wav, sr, spect = f5tts.infer(
            ref_file=audio_path,
            ref_text=ref_text,
            gen_text=gen_text,
            file_wave=output_wave_path,
            seed=-1  # Using random seed (-1)
        )
    except Exception as e:
        return jsonify({"error": f"F5TTS inference failed: {str(e)}"}), 500

    return send_file(output_wave_path, mimetype='audio/wav')
if __name__ == '__main__':
    app.run(debug=True)